#!/bin/bash 

NODE1_CONFDIR=/tmp/backup_htmf_conf

echo "Welcome to $0, a tool to install htmf/Smart Card 2.0"
runningid=`id -u`
if [ "x${runningid}" != "x0" ] ; then
    echo "must run as root eg: sudo $0"
    exit
fi

if [ -r /usr/local/environment ] ; then
	. /usr/local/environment
else
	echo "/usr/local/environment missing"
	exit
fi


randompass() {
        MATRIX="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
        LENGTH="8"
        while [ "${n:=1}" -le "$LENGTH" ] ; do
                PASS="$PASS${MATRIX:$(($RANDOM%${#MATRIX})):1}"
                let n+=1
        done
        echo "$PASS"
}


replaceconffile() {
    tofile=$1
    fromfile=$2
    
    if [ -f "${tofile}" ] ; then
	echo mv "${tofile}" "${tofile}.bak"
    fi
    
    if [ -f "${fromfile}" ] ; then
	echo cp "${fromfile}" "${tofile}"
    else
	echo "${fromfile} not found, exiting, did you run 921_copy_htmf_conf.sh on node1?"
	exit
    fi
    
}

echo "This will make all your issued cards unusable in the new installation since all old CA:s and certificates will be removed"
echo "Enter to continue, ctrl-c to abort"
echo
read a

secondarynode=n
echo
echo "Will this node be a secondary node?"
echo "y/N (default:n) >"
read secondarynode
if [ "x$secondarynode" = "xy" -o "x$secondarynode" = "xY" ] ; then
    secondarynode=y
    echo "you need to put properties in place yourself from node one to /tmp/htmf_conf_bak"
    echo "Run <syscheck>/related-availabe/921_copy_htmf_conf.sh on node1"

    replaceconffile "${NODE1_CONFDIR}/hardtokenmgmt.properties" \ 
    "${HTMF_HOME}/hardtokenmgmt.properties"
    replaceconffile "${NODE1_CONFDIR}/autogenerated_hardtokenmgmt.properties" \
	"${HTMF_HOME}/autogenerated_hardtokenmgmt.properties"
    replaceconffile "${NODE1_CONFDIR}/global.properties" \
	"${HTMF_HOME}/src/resources/globalsettings/global.properties"
    replaceconffile "${NODE1_CONFDIR}/jarsigner.jks" "${HTMF_HOME}/jarsigner.jks"
    replaceconffile "${NODE1_CONFDIR}/ejbca.properties" "${EJBCA_HOME}/conf/ejbca.properties"
    replaceconffile "${NODE1_CONFDIR}/database.properties" \
	"${EJBCA_HOME}/conf/database.properties"
    replaceconffile "${NODE1_CONFDIR}/keystore.jks" \
	"${JBOSS_HOME}/server/default/conf/keystore/keystore.jks"
    replaceconffile "${NODE1_CONFDIR}/truststore.jks" \
	"${JBOSS_HOME}/server/default/conf/keystore/truststore.jks"
    echo "do remember to remove the files in ${NODE1_CONFDIR} when you've tested all works ok here on node2"

fi

primecard=n
echo
echo "Will you use PrimeCard as CA Token?"
echo "y/n (default:n) >"
read inputprimecard
if [ "x$inputprimecard" = "xy" -o "x$inputprimecard" = "xY" ] ; then
    primecard=y
fi


mysql=n
echo 
echo "Will you use Mysql as Database layer?"
echo "y/n (default:n) >"
read inputmysql
if [ "x$inputmysql" = "xy" -o "x$inputmysql" = "xY" ] ; then
    mysql=y



### input ####
    defmysqladminroot=root
    echo
    echo "We'll need your MySQL admin username to setup the database for you?"
    echo -n "mysql-admin-root [${defmysqladminroot}]>"
    read mysqladminroot 
    if [ "x${mysqladminroot}" = "x" ] ; then
	mysqladminroot=${defmysqladminroot}
    fi
    
    defmysqladminpass=
    echo
    echo "We'll need your MySQL admin pass to setup the database for you?"
    echo -n "mysql-admin-pass [${defmysqladminpass}]>"
    read mysqladminpass
    if [ "x${mysqladminpass}" = "x" ] ; then
        mysqladminpass=${defmysqladminpass}
    fi
    
    defmysqlserverhostname=localhost
    echo
    echo "What is the MySQL hostname?"
    echo -n "mysql-serverhostname [${defmysqlserverhostname}]>"
    read mysqlserverhostname
    if [ "x${mysqlserverhostname}" = "x" ] ; then
        mysqlserverhostname=${defmysqlserverhostname}
    fi
    
    defmysqlejbcadbname=ejbca
    echo
    echo "What do you want the ejbca db to be called?"
    echo -n "mysql-ejbca-dbname [${defmysqlejbcadbname}]>"
    read mysqlejbcadbname
    if [ "x${mysqlejbcadbname}" = "x" ] ; then
        mysqlejbcadbname=${defmysqlejbcadbname}
    fi
    
    defmysqlejbcauser=ejbca
    echo
    echo "Select a MySQL ejbca username used to connect to the database from ejbca"
    echo -n "mysql-ejbca-user [${defmysqlejbcauser}]>"
    read mysqlejbcauser
    if [ "x${mysqlejbcauser}" = "x" ] ; then
        mysqlejbcauser=${defmysqlejbcauser}
    fi
    
    mysqlejbcapass=`randompass`
    
fi

defjarsignerpass=foo123
echo
echo "Enter the password for the jarsigner present in the 'htmf' directory"
echo "Make sure the key alias is 'jarsigner'!!!"
echo -n "jarsignerpass [${defjarsignerpass}]>"
read jarsignerpass
if [ "x${jarsignerpass}" = "x" ] ; then
    jarsignerpass=${defjarsignerpass}
fi


InstallLogFile="/tmp/smartcard20-setup.$$"
echo "To follow the verbose output of the install in a new screen run: # sudo tail -f $InstallLogFile"

#### new jboss 
	echo -n "Step 1/9 Installing a fresh copy of JBoss: "
	/etc/init.d/jboss stop >> ${InstallLogFile} 2>&1
        checkIfJbossIsRunning=`ps -ef | grep java | grep jboss | grep -v grep | awk '{print $2}'`
	if [ "x${checkIfJbossIsRunning}" != "x" ] ; then
		sleep 5 
        	checkIfJbossIsRunning=`ps -ef | grep java | grep jboss | grep -v grep | awk '{print $2}'`
		if [ "x${checkIfJbossIsRunning}" != "x" ] ; then
			kill -9 ${checkIfJbossIsRunning} 
		fi
	fi	

	rm -rf ${JBOSS_HOME}
	mkdir /usr/local/jboss-new 	 
	cd /usr/local/jboss-new 	 
	unzip ${SC20_DISTFILES}/jboss-4.2.3.GA-jdk6.zip >> ${InstallLogFile} 2>&1 	 
	mv jboss-4.2.3.GA ${JBOSS_HOME} 	 
	cd /usr/local/ 	 
	rm -rf /usr/local/jboss-new
	cp ${MYSQLDRIVER} ${JBOSS_HOME}/server/default/lib
	${SC20_DISTFILES}/jboss-server-switch-log-level.pl INFO >> ${InstallLogFile} 2>&1
	chown -R jboss.jboss ${JBOSS_HOME}
	echo "ok"


#### mysql config
	if [ "x$mysql" = "xy" ] ;then
	   echo -n "Step 2/9 Setting up mysql: "
	   #mysql code conf + jar 	
	   #### creating mysql db ####

	   echo 'show tables' | mysql --user=$mysqladminroot --password=$mysqladminpass $mysqlejbcadbname >/dev/null 2>&1
	   if [ $? -eq 0 ] ; then
		echo
		echo "database $mysqlejbcadbname does already exist, do you want to start fresh (I'll delete it and add a new ...)?"
		echo -n "drop-old-db y/n [y]>"
		read drop
		if [ "x$drop" = "xy" -o "x$drop" = "xY" -o "x$drop" = "x" ] ; then
			mysqladmin drop --user=$mysqladminroot --password=$mysqladminpass $mysqlejbcadbname 
        	else
			echo
			echo "ok, so now you need to sort this manually, then rerun me ( $0 )"
			exit 1
        	fi
		
           fi
	
	mysqladmin create --user=$mysqladminroot --password=$mysqladminpass $mysqlejbcadbname 
	if [ $? -ne 0 ] ; then
		echo "failed to create mysql database, you need to do it your self"
		exit 2	
	fi

	#### creating mysql user ####

	echo "grant all privileges on ${mysqlejbcadbname}.* to ${mysqlejbcauser}@${mysqlserverhostname} identified by '${mysqlejbcapass}';" | mysql mysql --user=$mysqladminroot --password=$mysqladminpass
	if [ $? -ne 0 ] ; then
		echo "failed to create mysql ejbca user , you need to do it your self"
		exit 3
	fi

	echo "ok"
fi

### setting up htmf options

	echo -n "Step 3/9 Setting properties in htmf/ejbca: "

	if [ "x$secondarynode" != "xy" ] ; then
	### htmf props
            su -p -s /bin/sh jboss -c "cp ${HTMF_HOME}/hardtokenmgmt.properties.sample ${HTMF_HOME}/hardtokenmgmt.properties "  >> ${InstallLogFile} 2>&1
            su -p -s /bin/sh jboss -c "perl -pi -e 's/^#build.as.application=true/build.as.application=true/' ${HTMF_HOME}/hardtokenmgmt.properties"
#           su -p -s /bin/sh jboss -c "perl -pi -e 's/^# applet.title=.*/applet.title=Welcome to SmartCard2.0/' ${HTMF_HOME}/hardtokenmgmt.properties"
#           su -p -s /bin/sh jboss -c "perl -pi -e 's/^#installpkg.appname=.*/installpkg.appname=SmartCard2.0/' ${HTMF_HOME}/hardtokenmgmt.properties"
#           su -p -s /bin/sh jboss -c "perl -pi -e 's/^#installpkg.startmenu=.*/installpkg.startmenu=SmartCard2.0/' ${HTMF_HOME}/hardtokenmgmt.properties"
#           su -p -s /bin/sh jboss -c "perl -pi -e 's/^# ws.hostname=localhost/ws.hostname=smartcard20.demo/' ${HTMF_HOME}/hardtokenmgmt.properties"
            su -p -s /bin/sh jboss -c "perl -pi -e 's/^#customproject.location=.*/customproject.location=\/usr\/local\/htmf_custom_project/' ${HTMF_HOME}/hardtokenmgmt.properties"
            su -p -s /bin/sh jboss -c "perl -pi -e 's/^jwsdemo.title=Welcome to ToLiMa/jwsdemo.title=Welcome to Smartcard 2.0/' ${HTMF_HOME}/hardtokenmgmt.properties"


	### settings for jarsigner
#jarsigner.keystore=jarsigner.jks
#jarsigner.passphrase=foo123
#jarsigner.alias=jarsigner
            su -p -s /bin/sh jboss -c "perl -pi -e 's/^#jarsigner.keystore=jarsigner.jks/jarsigner.keystore=jarsigner.jks/' ${HTMF_HOME}/hardtokenmgmt.properties"
            su -p -s /bin/sh jboss -c "perl -pi -e 's/^#jarsigner.passphrase=foo123/jarsigner.passphrase=${jarsignerpass}/' ${HTMF_HOME}/hardtokenmgmt.properties"
	    
	

	### mysql conf
	    if [ "x$mysql" = "xy" ] ;then
        	su -p -s /bin/sh jboss -c "cp ${EJBCA_HOME}/conf/database.properties.sample ${EJBCA_HOME}/conf/database.properties "  >> ${InstallLogFile} 2>&1
		su -p -s /bin/sh jboss -c "perl -pi -e \"s/#database.name=mysql/database.name=mysql/\" ${EJBCA_HOME}/conf/database.properties"
		su -p -s /bin/sh jboss -c "perl -pi -e \"s/#datasource.mapping=mySQL/datasource.mapping=mySQL/\" ${EJBCA_HOME}/conf/database.properties"
		su -p -s /bin/sh jboss -c "perl -pi -e \"s/#database.url=jdbc:mysql:\/\/127.0.0.1:3306\/ejbca$/database.url=jdbc:mysql:\/\/127.0.0.1:3306\/${mysqlejbcadbname}/\" ${EJBCA_HOME}/conf/database.properties"
		su -p -s /bin/sh jboss -c "perl -pi -e \"s/#database.driver=com.mysql.jdbc.Driver/database.driver=com.mysql.jdbc.Driver/\" ${EJBCA_HOME}/conf/database.properties"
		su -p -s /bin/sh jboss -c "perl -pi -e \"s/#database.username=ejbca/database.username=${mysqlejbcauser}/\" ${EJBCA_HOME}/conf/database.properties"
		su -p -s /bin/sh jboss -c "perl -pi -e \"s/#database.password=ejbca/database.password=${mysqlejbcapass}/\" ${EJBCA_HOME}/conf/database.properties"
	    fi

	fi # not node2

	### primecard props
	if [ "x$primecard" = "xy" ] ;then
	    cd ${PRIMECARD_HOME}/
	    ./bin/caTokenCard.sh >> ${InstallLogFile} 2>&1
	    
		#primecard setting in ejbca.properies
		# hwtoken -> /usr/local/primecard/caTokenClasses-1.6-3.5/
	    
	    if [ "x$secondarynode" != "xy" ] ; then
		
        	su -p -s /bin/sh jboss -c "cp ${EJBCA_HOME}/conf/ejbca.properties.sample ${EJBCA_HOME}/conf/ejbca.properties"
        	su -p -s /bin/sh jboss -c "perl -pi -e 's#^\#hwtoken_classes=../primeCard/caTokenClasses-1.5#hwtoken_classes=/usr/local/primecard/caTokenClasses-1.6-3.5#' ${EJBCA_HOME}/conf/ejbca.properties"
	    fi
	    
	    filename=`./bin/changePIN.sh listkeys | grep 'List of keys on card written to file' | perl -ane 'm/List of keys on card written to file\ (.*)\./, print "$1"'`
	    mv $filename ${HTMF_HOME}/active-catoken.txt
	    chown jboss.jboss ${HTMF_HOME}/active-catoken.txt
	    chmod 644 ${HTMF_HOME}/active-catoken.txt
	    
	fi
	
	
	echo "ok"



#### ejbca bootstrap
	echo -n "Step 4/9 Running ejbca bootstrap (prepairing the CA for setup): "
	cd ${EJBCA_HOME}

	su -p -s /bin/sh jboss -c "ant bootstrap" >> ${InstallLogFile} 2>&1
	if [ $? -eq 0 ] ; then
		echo "ok"
		rm -f $antbootstrapfile 
	else
		echo
		echo "FAILED: ant bootstrap failed, see file: ${InstallLogFile} for more info"
		exit 1
	fi


#### start jboss for the installing

	echo -n "Step 5/9 Starting jboss: "
	/etc/init.d/jboss start	>> ${InstallLogFile} 2>&1
	while true ; do
		sleep 10
		if [ -e ${JBOSS_HOME}/server/default/log/server.log ]; then
			startedgrep=`grep 'INFO.*Server.*JBoss.*MX MicroKernel.*4.*build: SVNTag=JBoss_.*date=.*Started in' ${JBOSS_HOME}/server/default/log/server.log` 2>&1 > /dev/null
		else
			sleep 10 # Wait a few more seconds
			startedgrep=`grep 'INFO.*Server.*JBoss.*MX MicroKernel.*4.*build: SVNTag=JBoss_.*date=.*Started in' ${JBOSS_HOME}/server/default/log/server.log` 2>&1 > /dev/null
		fi
		if [ "x${startedgrep}" != "x" ] ; then
			break;
		fi
	done	
	echo "ok"

	rm -f $HTMF_HOME/cacerts/* 

#### ejbca:setup
	echo -n "Step 6/9 Running ejbca:setup, Now you will have to answer some questions about this installation: "

	cd $HTMF_HOME
	if [ "x$secondarynode" != "xy" ] ; then
       	    su -p -s /bin/sh jboss -c "ant ejbca:setup" 
            if [ $? -eq 0 ] ; then
		echo "Step 6/9 ejbca:setup: ok"
            else
		echo
                echo "FAILED: ejbca:setup failed"
                exit 5
            fi
	fi

### and ant
        echo -n "Step 7/9 Running ant in ${HTMF_HOME}, building the code: "
	if [ "x$secondarynode" != "xy" ] ; then

	    if [ -x ${HTMF_HOME}/custom-settings-script.sh ] ; then
		${HTMF_HOME}/custom-settings-script.sh >> ${InstallLogFile} 2>&1
	    fi
	fi
       	su -p -s /bin/sh jboss -c "cd $HTMF_HOME ; ant"  >> ${InstallLogFile} 2>&1
        if [ $? -eq 0 ] ; then
                echo "ok"
        else
		echo
                echo "FAILED: ant in $HTMF_HOME: failed, see file: ${InstallLogFile} for more info"
                exit 6
        fi

### and ant deploy
        echo -n "Step 8/9 Running ant deploy in $HTMF_HOME, building the client-app-installer: "
       	su -p -s /bin/sh jboss -c "cd $HTMF_HOME ; ant deploy" >> ${InstallLogFile} 2>&1
        if [ $? -eq 0 ] ; then
        	echo "ok"
        else
                echo "FAILED: ant deply in $HTMF_HOME: failed, see file: ${InstallLogFile} for more info"
                exit 7
        fi
	

#### restart jboss

        echo -n "Step 9/9 Restarting Jboss: "
	/etc/init.d/jboss stop >> ${InstallLogFile} 2>&1
        checkIfJbossIsRunning=`ps -ef | grep java | grep jboss | grep -v grep | awk '{print $2}' `
        if [ "x${checkIfJbossIsRunning}" != "x" ] ; then
                sleep 5
                kill -9 ${checkIfJbossIsRunning}
        fi       

	sleep  10
	/etc/init.d/jboss start >> ${InstallLogFile} 2>&1

	i=0
	while true ; do
		sleep 10
		startedgrep=`grep 'INFO.*Server.*JBoss.*MX MicroKernel.*4.*build: SVNTag=JBoss_.*date=.*Started in' ${JBOSS_HOME}/server/default/log/server.log` 2>&1 > /dev/null
		if [ "x${startedgrep}" != "x" ] ; then
			break;
		fi
		if [ "x$i" == "x12" ] ; then
			echo "jboss not started in 120 secs, maybe you're on a slow machine or something went wrong"
			break;
		fi
	done
			
	echo "ok"

#### success

	
	if [ "x$primecard" = "xy" ] ; then
	    	echo
		echo "activating the CA:s"
		/usr/local/htmf/src/inst/smartcard20/activate-cas.sh
		echo "to activate CA:s again (after jboss or server restart) run: /usr/local/htmf/src/inst/smartcard20/activate-cas.sh"
	    	echo 
	fi
	
	echo 
	echo 
	echo "$0 finished"
	echo "now open: https://<hostname>:8442/htmf/isa.jsp to start with the superadmin card"
	echo "then: https://<hostname>:8442/htmf/ to start issuing cards"
	echo 
	echo 
	exit 0

